import logging
from typing import Dict, List, Any
from collections import defaultdict

from services.patent_analysis_service import PatentAnalysisService

logger = logging.getLogger(__name__)

class TableGenerationService:
    def __init__(self):
        self.analysis_service = PatentAnalysisService()
    
    async def generate_table1(self, patents: List[Dict[str, Any]], topic_name: str) -> Dict[str, Any]:
        """生成表1: Topic数据表"""
        logger.info("生成Topic数据表")
        
        # 获取发明人分析结果
        inventors_analysis = await self.analysis_service.analyze_inventors(patents)
        
        # 按年份统计专利
        years_data = defaultdict(lambda: defaultdict(int))
        years_details = defaultdict(lambda: defaultdict(list))
        
        for patent in patents:
            pub_date = patent.get('publication_date', '')
            year = self._extract_year_from_date(pub_date)
            
            inventor_names = self.analysis_service._parse_inventor_names(patent.get('inventor_name', []))
            applicant_name = patent.get('applicant_name', '')
            
            for inventor_name in inventor_names:
                if inventor_name.strip():
                    key = f"{inventor_name}|{applicant_name}"
                    years_data[key][year] += 1
                    years_details[key][year].append({
                        '_id': patent.get('_id'),
                        'invention_title': patent.get('invention_title', ''),
                        'abstract': patent.get('abstract', ''),
                        "publication_date": patent.get("publication_date", ""),
                        "applicant_name": patent.get("applicant_name", ""),
                        "inventor_name": patent.get("inventor_name", []),
                        "applicant_address": patent.get("applicant_address", "")
                    })
        
        # 构建表格数据
        table1 = {
            'years': ['2023', '2024', 'all'],
            'data': {},
            'details': {}
        }
        
        for inventor_key, year_counts in years_data.items():
            val_2023 = year_counts.get('2023', 0)
            val_2024 = year_counts.get('2024', 0)
            val_all = val_2023 + val_2024
            
            table1['data'][inventor_key] = {
                '2023': val_2023,
                '2024': val_2024,
                'all': val_all
            }
            
            table1['details'][inventor_key] = {
                '2023': years_details[inventor_key].get('2023', []),
                '2024': years_details[inventor_key].get('2024', []),
                'all': years_details[inventor_key].get('2023', []) + years_details[inventor_key].get('2024', [])
            }
        
        return table1
    
    async def generate_table2(self, patents: List[Dict[str, Any]]) -> Dict[str, Any]:
        """生成表2: All数据表"""
        logger.info("生成All数据表")
        
        # 获取发明人分析结果
        inventors_analysis = await self.analysis_service.analyze_inventors(patents)
        
        table2 = {
            'years': ['2023', '2024', 'all'],
            'data': {},
            'details': {}
        }
        
        for inventor_key, analysis in inventors_analysis.items():
            all_patents = analysis['all_patents']
            
            # 按年份统计所有专利
            count_2023 = 0
            count_2024 = 0
            details_2023 = []
            details_2024 = []
            
            for patent in all_patents:
                pub_date = patent.get('publication_date', '')
                year = self._extract_year_from_date(pub_date)
                
                patent_info = {
                    '_id': patent.get('_id'),
                    'invention_title': patent.get('invention_title', ''),
                    'abstract': patent.get('abstract', ''),
                    "publication_date": patent.get("publication_date", ""),
                    "applicant_name": patent.get("applicant_name", ""),
                    "inventor_name": patent.get("inventor_name", []),
                    "applicant_address": patent.get("applicant_address", "")
                }
                
                if year == '2023':
                    count_2023 += 1
                    details_2023.append(patent_info)
                elif year == '2024':
                    count_2024 += 1
                    details_2024.append(patent_info)
            
            count_all = count_2023 + count_2024
            
            table2['data'][inventor_key] = {
                '2023': count_2023,
                '2024': count_2024,
                'all': count_all
            }
            
            table2['details'][inventor_key] = {
                '2023': details_2023,
                '2024': details_2024,
                'all': details_2023 + details_2024
            }
        
        return table2
    
    async def generate_table3(self, table1: Dict[str, Any], table2: Dict[str, Any]) -> Dict[str, Any]:
        """生成表3: Topic/All比例数据表"""
        logger.info("生成Topic/All比例数据表")
        
        table3 = {
            'years': ['2023', '2024', 'all'],
            'data': {}
        }
        
        for inventor_key in table1['data']:
            if inventor_key in table2['data']:
                table1_data = table1['data'][inventor_key]
                table2_data = table2['data'][inventor_key]
                
                ratios = {}
                for year in ['2023', '2024', 'all']:
                    t1_count = table1_data.get(year, 0)
                    t2_count = table2_data.get(year, 0)
                    
                    if t2_count != 0:
                        ratio = t1_count / t2_count
                    else:
                        ratio = 0.0
                    
                    ratios[year] = round(ratio, 3)
                
                table3['data'][inventor_key] = ratios
        
        return table3
    
    def _extract_year_from_date(self, date_str: str) -> str:
        """从日期字符串中提取年份"""
        if not date_str:
            return 'unknown'
        
        try:
            # 支持多种日期格式
            if len(date_str) >= 4:
                year = date_str[:4]
                if year.isdigit():
                    return year
            return 'unknown'
        except:
            return 'unknown'
